<?php

session_start();

//print_r($_SESSION);

include_once("db_login.php");
$cnx_status = connect_to_db();
if (!$cnx_status) {
	die("Could not connect to database: " . mysql_error());
}


//echo "AUTH IS " . $_SESSION["auth"] . "<br />";

if (!$_SESSION['auth']) {
	echo "Please <a href=\"login_form.php\">log in</a> to the MoDD website.";
	echo "</body></html>";
	
	exit;
}

// need to figure out WHO is doing something
// and WHAT they are doing
//
// then set variables for this to refer to later.


$my_uid    = $_SESSION["uid"];

if (isset($_POST['user_submit'])) {
	$view_uid = $_POST['user_list'];
	if (strcmp($view_uid,"none") != 0){
		$_SESSION["view_uid"] = $view_uid;
	}
	else {
		unset($_SESSION["view_uid"]);
	}
}

$self   = $_SERVER['PHP_SELF'];

$who  =  NULL;
$what =  NULL;

$ADMIN = "admin";
$USER  = "user";
$PROV  = "provider";

$VIEW = "view";
$SAVE = "save";
$EDIT = "edit";

$the_username = $_SESSION["username"];

// by default, you're in a 'view' state
$what = $VIEW;

$who = getPermissions($my_uid);

if ($_POST['edit']) {
	$what = $EDIT;
}
else if ($_POST['save']) {
	$what = $VIEW;
}

if ( strcmp($what,$VIEW)==0 ) {
	if (strcmp($who,$USER) == 0) {
		saveUserComments();
	} else if (strcmp($who,$PROV)==0) {
		saveProvComments();
	}
}

render_header();
render_start();

if ( strcmp($who,$ADMIN)==0 ) {
	render_stats();
}

if ( (strcmp($who,$PROV)==0) or (strcmp($who,$ADMIN)==0) ) {
	render_user_list();

	if (isset($_SESSION['view_uid'])) {
		showSamplesFor($_SESSION["view_uid"]);
	}
}
else if (strcmp($who, $USER)==0) {
	showSamplesFor($_SESSION["uid"]);
}



function showSamplesFor($show_uid) {

	global $who, $what, $PROV, $USER, $ADMIN, $VIEW, $SAVE, $EDIT;

	$list_components = array();
	
	$select = ' SELECT ';
	$from   = ' FROM ';
	
	$query = $select . " sample_id,time,glucose,user_comment,cp_comment " . $from . " `sample` " . 
			" WHERE " . " (`sample`.user_id=$show_uid) ORDER BY time";

	$sample_ids = mysql_query($query);
	
	while ($result_row = mysql_fetch_row($sample_ids)) {
		$sample_id = $result_row[0];
		$list_components[$sample_id] = array();
		$list_components[$sample_id]["time"] = $result_row[1]; 
		$list_components[$sample_id]["glucose"] = $result_row[2]; 
		$list_components[$sample_id]["user_comment"] = $result_row[3];
		$list_components[$sample_id]["cp_comment"] = $result_row[4];
	
	
		//get all the audio files
		$audio_query = $select . " location,audio_id " . $from . " `audio` " . " WHERE " . 
																" (`audio`.sample_id=$sample_id) ";
		$audio_locs = mysql_query($audio_query);
		$audio_files = array();
		while ($res_row_2 = mysql_fetch_array($audio_locs, MYSQL_ASSOC)) {
			//echo "Got for item location:" . $res_row_2[0] . " & length:" . $res_row_2[1] ."<br />";
			array_push($audio_files, array($res_row_2["location"], $res_row_2["audio_id"]));
		}
		$list_components["$sample_id"]["audio"] = $audio_files;
		
		
		// get all the image files
		$image_query = $select . " location " . $from . " `image` " . " WHERE " . 
																" (`image`.sample_id=$sample_id) ";
		$image_locs = mysql_query($image_query);
		$image_files = array();
		while ($res_row_2 = mysql_fetch_array($image_locs, MYSQL_ASSOC)) {
			//echo "Got for item location:" . $res_row_2[0] . " & length:" . $res_row_2[1] ."<br />";
			array_push($image_files, $res_row_2["location"]);
		}
		$list_components["$sample_id"]["image"] = $image_files; 
	}

	
	$name_query = "SELECT firstname, lastname FROM user WHERE user.user_id=$show_uid";
	$name_res = mysql_query($name_query);
	$name_data = mysql_fetch_array($name_res, MYSQL_ASSOC);
	
	echo ("<h3> Samples for $name_data[firstname] $name_data[lastname] </h3>\n");

	echo(
	'<table width="100%"  border="1" align="center">
	  <tr>
		<th width="5%" class="table_header" scope="col">Sample ID </th>
		<th width="10%" class="table_header" scope="col">Time</th>
		<th width="5%" class="table_header" scope="col">Glucose</th>
		<th width="20%" class="table_header" scope="col">Images</th>
		<th width="15%" class="table_header" scope="col">Audio</th>');
	
	
	if ( strcmp($what,$VIEW) == 0 ) {
		$button_name = "edit";
		$button_val  = "Edit";
	}
	else if (strcmp($what, $EDIT) == 0) {
		$button_name = "save";
		$button_val  = "Save";
	}
	
	/* The user comments column */
	if (strcmp($who, $USER) == 0) {
		echo("<th width='25%' class='table_header' scope='col'>" .
		"<form action=\" " . $_SERVER[PHP_SELF] . "\" method=\"POST\">\n" .
		"Comments <input type=\"submit\" name=$button_name value=$button_val>\n" .
		"</th>");
	}
	else {
		echo ("<th width='25%' class='table_header' scope='col'> Comments </th> \n");
	}
	/* end user comments column*/

	/* The provider comments column */
	if (strcmp($who, $PROV) == 0) {
		echo("<th width='25%' class='table_header' scope='col'>" .
		"<form action=\" " . $_SERVER[PHP_SELF] . "\" method=\"POST\">\n" .
		"Care Provider's Comments <input type=\"submit\" name=$button_name value=$button_val>\n" .
		"</th></tr>");
	} 
	else {
		echo ("<th width='25%' class='table_header' scope='col'> Care Provider's Comments </th></tr> \n");
	}
	/* end provider comments column */


	$even_row = false;
	
	foreach ($list_components as $id => $data) {
	 
		 $row_tag = ($even_row) ? "class=\"even_row\"" : "class=\"odd_row\"";
		 
		 echo "<tr $row_tag>"; 
		 echo "<td ALIGN=\"center\"><b>$id</b></td>";
		 echo "<td>$data[time]</td>";
		 echo "<td>$data[glucose]</td>";
		 
		 // show each image.
		 echo "<td>";
		 foreach ($data["image"] as $img) {
			echo "<img src=\"samples/sample_$id/image/$img\" style=\"padding:10px\"/><br />";
		 } 
		 echo "</td>";
		 
		 
		 echo "<td>";
		 foreach ($data["audio"] as $aud) {
		 	
			 $file_path = "samples/sample_$id/audio/";
			
			
			 $audio_file_location = $aud[0];
			 $audio_file_id = $aud[1];
			 
			 $file_parts = explode(".",$audio_file_location);
			 if ( (file_exists($file_path.$file_parts[0].".mp3")) and 
			      (filesize($file_path.$file_parts[0].".mp3") > 0) ) {
		 	 
				 echo "<a href=\"scripts/get_file.php?sample_id=$id&file_type=mp3&file_id=$audio_file_id\">".		
				 "$file_parts[0].mp3</a><br />";
			} else {
				echo "<a href=\"scripts/get_file.php?sample_id=$id&file_type=amr&file_id=$audio_file_id\">".		
				 "$file_parts[0].mp3</a><br />";
			}
		 } 
		 echo "</td>";
		 
		 
		 echo "<td>";
		 if ( (strcmp($what,$EDIT) == 0) && (strcmp($who,$USER) == 0) )  {
			echo "<textarea name=\"user_sample$id\" cols=\"30\" rows=\"10\">$data[user_comment]</textarea>";
		 }
		 else {
			echo "$data[user_comment]";
		 }
		 echo "</td>";
	
	
		echo "<td>";
		if ( (strcmp($what,$EDIT) == 0) && (strcmp($who,$PROV)==0) ){
			echo "<textarea name=\"cp_sample$id\" cols=\"30\" rows=\"10\">$data[cp_comment]</textarea>";
		}
		else {
			echo "$data[cp_comment]";
		}
		
		echo "</tr>";
		
		$even_row = !$even_row;
	 
	} // end bracket for loop that goes through all the samples
	
	echo("</table>");
	echo "</form>";
	
	render_end();
}

function render_stats() {

// TODO: ADD DELETE ACCOUNT BUTTON

	$user_stats_query   = "SELECT user_id, username, firstname, lastname, last_log_time FROM user ".
						  "WHERE permission=\"U\"";
	$user_stats_res     = mysql_query($user_stats_query);
	
	
	echo("<h3> Registered Users </h3>");
	
	echo("<table BORDER=\"1\" WIDTH=\"75%\">\n");
	echo("<tr>\n");
	echo("<th>User ID</th>\n");
	echo("<th>Username</th>\n");
	echo("<th>First name</th>\n");
	echo("<th>Last name</th>\n");
	echo("<th>Last log</th>\n");
	echo("<th>Last sample</th>\n");
	echo("<th>Number samples</th>\n");
	echo("</tr>\n");
	 
	
	while ($user_row = mysql_fetch_array($user_stats_res, MYSQL_ASSOC)) {
		
		$this_user_id = $user_row["user_id"];
		
		echo("<tr>\n");
		echo("<td>$this_user_id</td>\n");
		echo("<td>$user_row[username]</td>\n");
		echo("<td>$user_row[firstname]</td>\n");
		echo("<td>$user_row[lastname]</td>\n");
		echo("<td>$user_row[last_log_time]</td>\n");
		
		
		$last_sample_query   = "SELECT time FROM sample WHERE user_id=$this_user_id ORDER BY time DESC";
		$last_sample_res     = mysql_query($last_sample_query);
		$last_sample_data    = mysql_fetch_array($last_sample_res);
		
		$last_sample = $last_sample_data[0];
		
		
		
		$num_samples_query   = "SELECT COUNT(*) FROM sample WHERE user_id=$this_user_id";
		$num_samples_res     = mysql_query($num_samples_query);
		$num_sample_data    = mysql_fetch_array($num_samples_res);
		
		$num_samples = $num_sample_data[0];
	
		
		
		echo("<td>$last_sample</td>\n");
		echo("<td>$num_samples</td>\n");
		echo("</tr>");
	}
	
	echo("</table>");
	
	echo("<br /><HR WIDTH=\"100%\">");

}

function render_header() {
	echo (
	'<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
	<title>My Samples</title>
	<link href="moddweb.css" rel="stylesheet" type="text/css">
	</head>');
}

function render_start() {

	$name   = $_SESSION["name"];

	echo ('<body>');

	echo ('<table width="100%" border="0">');
	echo ("<tr><td WIDTH=\"80%\">&nbsp;</td>");
	echo ("<td ALIGN=right><a href=\"change_password.php\">change password</a></td>");
	echo ("<td ALIGN=right><a href=\"goodbye.php\">log out</a></td></tr>");
	echo ('<tr><td WIDTH="2%"><h2 class="nice_box"> Welcome, ' . $name . '!</h2></td></tr>');
	echo ("</table>");
	

}

function render_end() {
	echo ('</body></html>');
}

function render_user_list() {
	/* determine if you need to give admin the list of users  records to view */

	$query_res = mysql_query("SELECT user_id,firstname,lastname,permission FROM user");
	$reg_users = array();
	
	while ($row = mysql_fetch_array($query_res, MYSQL_ASSOC)) {
		//echo $row["firstname"];
		if (strcmp($row["permission"],"U") == 0) {
			$reg_users[$row["user_id"]] = $row["firstname"] . " " . $row["lastname"];
		}
	}
		
	echo "<br /> <br />";
	echo('<form action="' . $self . '" method="POST">
	<label>Select a user to view: </label><br />
	<SELECT NAME="user_list">
	<option VALUE="none"></option>');		
	
	foreach ($reg_users as $key => $value) {
		echo('<OPTION VALUE="' . $key . '">' . $value . "</option>");
	}
	echo ("</SELECT>
		<input type=\"submit\" name=\"user_submit\" value=\"View\">
		</form>");
}

function saveUserComments() {
	foreach ($_POST as $key => $value) {
		if (strpos($key, "user_sample") === 0) {
			$comment_id = substr($key,11);
			$comment_query = "UPDATE sample SET user_comment=\"$value\" WHERE sample_id=$comment_id";
			$res = mysql_query($comment_query);		
		}
	}
}

function saveProvComments() {
	foreach ($_POST as $key => $value) {
		if (strpos($key, "cp_sample") === 0) {
			$comment_id = substr($key,9);
			$comment_query = "UPDATE sample SET cp_comment=\"$value\" WHERE sample_id=$comment_id";		
			$res = mysql_query($comment_query);
		}
	}
}

function getPermissions($a_uid) {

	global $PROV, $ADMIN, $USER;

	$prmsn_query = "SELECT permission FROM user where user_id=$a_uid";		
	$res = mysql_query($prmsn_query);
	
	$prmsn_array = mysql_fetch_array($res, MYSQL_ASSOC);

	switch ($prmsn_array['permission']) {
		case "P":
			return $PROV;
		case "A";
			return $ADMIN;
		case "U":
			return $USER;
	}
}


?>
